package com.tengju.bff.interfaces.covercharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.tengju.bff.interfaces.covercharge.constant.TaskBizType;
import com.tengju.bff.interfaces.covercharge.constant.TaskStatusEnum;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceTask;
import com.tengju.bff.interfaces.covercharge.entity.vo.PersonalGiveImport;
import com.tengju.bff.interfaces.covercharge.entity.vo.PersonalGiveImportTaskResult;
import com.tengju.bff.interfaces.covercharge.entity.vo.TaskQuery;
import com.tengju.bff.interfaces.covercharge.entity.vo.TaskResultVo;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceTaskMapper;
import com.tengju.bff.interfaces.covercharge.service.ITaskService;
import com.tengju.bff.interfaces.covercharge.util.BeanMapperUtils;
import com.tengju.bff.interfaces.covercharge.util.DateTimeUtils;
import com.tengju.bff.interfaces.covercharge.util.ExcelExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class TaskServiceImpl extends ServiceImpl<ServiceTaskMapper, ServiceTask> implements ITaskService {


    @Autowired
    private ServiceTaskMapper taskMapper;

    @Override
    public Page<TaskResultVo> queryTaskList(Page page, TaskQuery taskQuery) {
        QueryWrapper<ServiceTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(taskQuery.getTaskNo()), "task_no", taskQuery.getTaskNo());
        queryWrapper.eq(StringUtils.isNotBlank(taskQuery.getApplicant()), "task_applicant", taskQuery.getApplicant());
        queryWrapper.eq(taskQuery.getTaskStatus() != null, "task_status", taskQuery.getTaskStatus());
        queryWrapper.like(StringUtils.isNotBlank(taskQuery.getTaskKey()), "task_key", taskQuery.getTaskKey());
        if (StringUtils.isNotBlank(taskQuery.getCreateStartTime()) && StringUtils.isNotBlank(taskQuery.getCreateEndTime())) {
            queryWrapper.ge("create_time", taskQuery.getCreateStartTime());
            queryWrapper.le("create_time", taskQuery.getCreateEndTime());
        }
        queryWrapper.orderByDesc("id");
        IPage<ServiceTask> pagelist = taskMapper.selectPage(page, queryWrapper);
        List<ServiceTask> taskList = pagelist.getRecords();
        List<TaskResultVo> taskResultList = Lists.newArrayList();

        for (ServiceTask task : taskList) {
            TaskResultVo resultVo = BeanMapperUtils.map(task, TaskResultVo.class);
            if (Objects.isNull(resultVo)) {
                continue;
            }
            TaskBizType type = TaskBizType.getInstance(resultVo.getBizType());
            resultVo.setBizType(Objects.isNull(type) ? null : type.getMsg());

            switch (task.getTaskStatus()) {
                case 1:
                    resultVo.setTaskStatus("处理中");
                    break;
                case 2:
                    resultVo.setTaskStatus("成功");
                    break;
                case 3:
                    resultVo.setTaskStatus("失败");
                    break;
                default:
                    break;
            }
            resultVo.setCreateTime(task.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            resultVo.setUpdateTime(task.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            taskResultList.add(resultVo);
        }
        page.setRecords(taskResultList);
        page.setTotal(pagelist.getTotal());
        return page;
    }

    /**
     * 下载导出文件
     *
     * @param response
     * @param filename
     * @throws IOException
     */
    @Override
    public void downloadFile(byte[] file, HttpServletRequest request, HttpServletResponse response, String filename) {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment;filename=" + ExcelExportUtil.getFileName(request, filename));
            response.setContentType("application/msexcel;charset=UTF-8");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            out.write(file);
        } catch (Exception ignored) {
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    /**
     * 违约金审核插入任务记录表
     * @param allSize      所有总量
     * @param des 任务描述
     * @param applicant 操作人
     * */
    @Override
    public PersonalGiveImportTaskResult rewardCreateTask(int allSize, String des,String applicant) {
        String key=DateTimeFormatter.ofPattern(DateTimeUtils.DEFAULT_DATE_TIME_FORMAT).format(LocalDateTime.now())+"_"+des;
        ServiceTask task = new ServiceTask();
        task.setTaskNo(String.valueOf(IdWorker.getId())).setTaskKey(key)
                .setBizType(TaskBizType.TYPE_1.getType()).
                setTaskSize(allSize).setTaskStatus(TaskStatusEnum.DEAL.getCode()).setTaskApplicant(applicant)
                .setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now())
        .setSuccessSize(0).setFailSize(0).setDealSize(0);
        int num = taskMapper.insert(task);
        PersonalGiveImportTaskResult taskResult = new PersonalGiveImportTaskResult();
        if (num > 0) {
            taskResult.setTaskResult(true);
            taskResult.setTaskNo(task.getTaskNo());
            taskResult.setTaskKey(task.getTaskKey());
            return taskResult;
        }
        taskResult.setTaskResult(false);
        taskResult.setErrorMsg("创建任务失败，请稍后重试");
        return taskResult;
    }
}
